<template>
  <div>
    <Card title="管理促销活动">
      <div class="operTime">
        <Row class="ptop20">
          <label class="select-return-type">活动状态：</label>
          <Col class="select-table-item">
            <Select v-model="searchOption.activityStatus" size="default" clearable>
              <Option
                v-for="item in activityStatusTableData"
                :value="item.code"
                :key="item.id"
                :label="item.name"
              ></Option>
            </Select>
          </Col>
          <label class="select-return-type space-left">活动类型：</label>
          <Col class="select-table-item">
            <Select v-if="accountType == 'store'" v-model="searchOption.activityType" size="default" clearable>
              <Option
                v-for="item in activityTypeTableStoreData"
                :value="item.code"
                :key="item.id"
                :label="item.name"
              ></Option>
            </Select>
            <Select v-else v-model="searchOption.activityType" size="default" clearable>
              <Option
                v-for="item in activityTypeTableChainData"
                :value="item.code"
                :key="item.id"
                :label="item.name"
              ></Option>
            </Select>
          </Col>
          <label class="select-return-type space-left">时间：</label>
          <DatePicker
            type="datetimerange"
            :options="optionTime"
            format="yyyy-MM-dd HH:mm:ss"
            @on-change="handleDateChange"
            :value="searchOption.dateValue"
            :editable="false"
            split-panels
            style="width: 21%"
          ></DatePicker>
          <label class="select-return-type space-left">活动名称：</label>
          <Col class="select-table-item order-no-col">
            <Input size="default" style="width: 100%" placeholder="请输入活动名称" v-model="searchOption.activityName"/>
          </Col>
        </Row>
        <Row class="ptop20">
          <Button icon="ios-search" type="primary" @click="onSearch" class="query-btn">查询</Button>
          <Button icon="ios-trash-outline" @click="onReset" class="reset-btn" type="warning">重置</Button>
        </Row>
      </div>
      <div class="tabsList">
        <Table
          class="table-all-width"
          :columns="columns"
          :data="data"
          :stripe="true"
          :border="true"
          :loading="Tableloading"
        >
        <template slot-scope="{ row, index }" slot="activityStore">
          <div>
            <span style="font-weight: 500;">{{ row.activityDistributeStatus == 0 ? '0' : row.activeStoreCount }}</span>
            <span v-if="row.activityDistributeStatus != 0" style="margin-left: 5px;color: #2D1FFF;" @click="handleShowActivityStore(index)">查看门店</span>
          </div>
        </template>
        <template slot-scope="{ row, index }" slot="actions">
          <div v-if="accountType == 'store'">
            <div v-if="row.activityCreateSource == 0">
              <Button icon="ios-eye" @click="handleShowActivityClick(index)" size="small" type="primary" style="margin-left: 5px;">查看</Button>
              <Button v-if="row.activityStatus == 1" icon="md-create" @click="handleEditActivityClick(index)" size="small" type="primary" style="margin-left: 5px;">编辑</Button>
              <Button v-if="row.activityStatus == 1" icon="md-create" @click="handleEndActivityClick(index)" size="small" type="primary" style="margin-left: 5px;">终止</Button>
              <Button v-if="row.activityStatus == 0" icon="md-create" @click="handleRestartActivityClick(index)" size="small" type="primary" style="margin-left: 5px;">重启</Button>
              <Button v-if="row.activityStatus == 0 || row.activityStatus == 2" icon="md-trash" @click="handleDeteleActivityClick(index)" size="small" type="error" style="margin-left: 5px;">删除</Button>
            </div>
            <div v-else>
              <Button icon="ios-eye" @click="handleShowActivityClick(index)" size="small" type="primary" style="margin-left: 5px;">查看</Button>
              <Button v-if="row.activityStatus == 2" icon="md-trash" @click="handleDeteleActivityClick(index)" size="small" type="error" style="margin-left: 5px;">删除</Button>
            </div>
          </div>
          <div v-else>
            <Button v-if="row.activityDistributeStatus == 0" icon="md-arrow-round-down" @click="handleDistributeActivityClick(index)" size="small" type="primary" style="margin-left: 5px;">下发</Button>
            <Button v-if="row.activityDistributeStatus == 1" icon="md-create" @click="handleUnSubscribeActivityClick(index)" size="small" type="primary" style="margin-left: 5px;">撤回</Button>
            <Button icon="ios-eye" @click="handleShowActivityClick(index)" size="small" type="primary" style="margin-left: 5px;">查看</Button>
            <Button v-if="row.activityStatus == 1 || row.activityStatus == 3" icon="md-create" @click="handleEditActivityClick(index)" size="small" type="primary" style="margin-left: 5px;">编辑</Button>
            <Button v-if="row.activityStatus == 1" icon="ios-stopwatch" @click="handleEndActivityClick(index)" size="small" type="primary" style="margin-left: 5px;">终止</Button>
            <Button v-if="row.activityStatus == 0" icon="md-create" @click="handleRestartActivityClick(index)" size="small" type="primary" style="margin-left: 5px;">重启</Button>
            <Button v-if="row.activityStatus == 0" icon="md-trash" @click="handleDeteleActivityClick(index)" size="small" type="error" style="margin-left: 5px;">删除</Button>
            <Button icon="md-analytics" @click="handleShowActivityEffect(index)" size="small" type="primary" style="margin-left: 5px;">活动效果</Button>
          </div>
          </template>
        </Table>
        <div style="margin-top: 10px;overflow: hidden">
          <div style="float: right;">
            <Page
              :total="total"
              :current.sync="pageNum"
              :page-size="pageSize"
              show-sizer
              @on-change="changePage"
              @on-page-size-change="changePageSize"
            />
          </div>
        </div>
        <sell-promotion ref="refSellPromotionModal" @submit='handleSubmit'></sell-promotion>
        <Modal
          :mask-closable="false"
          class-name="vertical-center-modal"
          v-model="showSubscribeActivityModal"
          title="下发促销活动冲突预选方案"
          width="40%"
        >
          <RadioGroup v-model="priorityTypeStr" vertical>
            <Radio label="集团下发的促销活动生效，自动终止门店冲突活动"></Radio>
            <Radio label="继续使用门店促销活动，集团促销下发时自动终止"></Radio>
          </RadioGroup>
          <div slot="footer">
            <Button style="margin-left: 8px" @click="handleSubscribeActivityCancel">取消</Button>
            <Button type="primary" @click="handleSubscribeActivitySure">确定</Button>
          </div>
        </Modal>
        <Modal
          :mask-closable="false"
          class="formTop"
          v-model="showActivityStoreModal"
          title="门店列表"
          width="40%"
        >
          <Table
            :columns="activityStoresTableColumns"
            :data="activityStoreList"
          >
          </Table>
          <div slot="footer">
            <Button type="primary" @click="handleActivityStoreListModalClose">关闭</Button>
          </div>
        </Modal>
        <Modal
          :mask-closable="false"
          class="formTop"
          v-model="showActivityEffectModal"
          title="活动效果"
          width="70%"
          @on-cancel="closeActivityEffectModal"
        >
          <div class="activity-effect-analysis">
            <span>活动分析</span>
            <div class="activity-effect-analysis-list">
              <div class="activity-effect-analysis-list-item" v-for="(item, index) in activityAnalysisListData">
                <img :src="item.img"/>
                <div class="activity-effect-analysis-list-item-right">
                  <p>{{ item.amount }}</p>
                  <p>{{ item.name }}</p>
                </div>
                <div class="activity-effect-analysis-list-item-separate"></div>
              </div>
            </div>
          </div>
          <div class="activity-effect-overview">
            <Row :gutter="20" style="padding-left: 10px">
              <span
                style="margin-left: 40px"
              >
                门店：
              </span>
              <span
                class="activity-effect-overview-store-name"
                @click="handleSelectStore"
              >
                {{ activityEffectStoreList.length > 0 ? '已选择'+activityEffectStoreList.length+'个门店' : '请选择门店' }}
              </span>
              <label class="select-return-type overview-dateLabel">时间：</label>
              <DatePicker
                type="daterange"
                :options="optionTime"
                format="yyyy-MM-dd hh:mm:ss"
                @on-change="handleActivityEffectDateChange"
                :value="activityEffectDateValue"
                :editable="false"
                split-panels
                style="width: 21%"
              ></DatePicker>
              <label
                :class="isSelectedShow7DayEffect ? 'activity-effect-overview-date-selected' : 'activity-effect-overview-date-normal'"
                @click="handleSelectShowDayCount(7)"
              >
                7天
              </label>
              <label
                :class="isSelectedShow15DayEffect ? 'activity-effect-overview-date-selected' : 'activity-effect-overview-date-normal'"
                @click="handleSelectShowDayCount(15)"
              >
                15天
              </label>
              <label
                :class="isSelectedShow30DayEffect ? 'activity-effect-overview-date-selected' : 'activity-effect-overview-date-normal'"
                @click="handleSelectShowDayCount(30)"
              >
                30天
              </label>
              <Button icon="ios-search" type="primary" @click="onSearchActivityEffect" class="query-btn">查询</Button>
              <Button icon="ios-trash-outline" @click="onResetActivityEffect" class="reset-btn" type="warning">重置</Button>
              <div class="activity-effect-overview-separate"></div>
              <div class="activity-effect-overview-list">
                <div class="activity-effect-overview-list-item" v-for="item in overviewListData">
                  <p class="activity-effect-overview-list-item-name">{{ item.name }}</p>
                  <p class="activity-effect-overview-list-item-value">{{ item.amount }}</p>
                </div>
              </div>
            </Row>
          </div>
          <div class="activity-effect-ranking">
            <span class="activity-effect-ranking-title">活动营业额排行榜</span>
            <span v-if="storeRankingData.length > 10" style="color: #F29D42;font-weight: 500;" @click="handleShowAllStoreRanking">查看全部</span>
            <Table
              width="550"
              class="table-all-width"
              :columns="activityEffectColumns"
              :data="storeRankingTableData"
              :stripe="true"
              :border="true"
              :loading="storeRankingTableloading"
            >
            </Table>
          </div>
          <div slot="footer">
          </div>
        </Modal>
        <Modal
          :mask-closable="false"
          v-model="showSelectStoreListModal"
          height="600"
          title="选择活动门店"
          width="40%"
        >
          <Table
            ref='activityEffectStoreListSelection'
            :columns="activityStoresSelectTableColumns"
            :data="statisticsStoreList"
            @on-selection-change="activityEffectStoreSelcted"
          >
          </Table>
          <div slot="footer">
            <Button style="margin-right: 65%;" @click="handleClearSelectedStore" type="warning">清空</Button>
            <Button style="margin-left: 8px" @click="handleActivityStoreModalCancel">取消</Button>
            <Button type="primary" @click="handleActivityStoreModalSure">确定</Button>
          </div>
        </Modal>
        <Modal
          :mask-closable="false"
          v-model="showAllStoreRankingModal"
          height="600"
          title="活动营业额排行榜"
          width="35%"
        >
          <Table
            width="550"
            class="table-all-width"
            :columns="activityEffectColumns"
            :data="storeRankingData"
            :stripe="true"
            :border="true"
            :height="600"
          >
          </Table>
          <div slot="footer">
            <Button type="primary" @click="handleStoreRankingModalClose">关闭</Button>
          </div>
        </Modal>
      </div>
    </Card>
  </div>
</template>

<script>
import sellPromotionModal from "./sellPromotionModal.vue"
import { Format } from "@/assets/util";
import storage from "@/libs/storage";
import {
  storeActivityManageSave, // 单店-保存/更新活动
  chainActivityManageSave, // 连锁-保存/更新活动
  storeActivityManageUpdateStatus, // 单店-更新活动状态
  storeActivityManageListPage, // 单店-分页查询活动列表
  chainActivityManageDistribute, // 连锁-发布活动
  chainActivityStoreQuery, // 连锁-活动门店查询
  chainActivityManageListPage, // 连锁-分页查询活动列表
  activityManageUnSubScribe, // 连锁-撤回活动下发
  chainActivityStatisticsInfo, // 连锁-活动效果-活动分析
  chainActivityStatisticsStoreChart, // 连锁-活动效果-活动营业额排行榜
  chainActivityStatisticsStoreList, // 连锁-查询活动关联门店列表
  activityManageDelete // 删除活动
} from "@/api/order";
import { generateRandom, buildTree } from "@/assets/util";
import activityRevenueImg from '../../assets/images/company-icon.jpg';

export default {
  data() {
    return {
      accountType: 'store', // 登录类型默认为单店
      Tableloading: true,
      modalFlag: "",
      showModal: false,
      showSubscribeActivityModal: false, // 下发活动模态窗
      showActivityStoreModal: false, // 活动门店模态窗
      showActivityEffectModal: false, // 活动效果模态窗
      showSelectStoreListModal: false, // 活动门店模态窗
      showAllStoreRankingModal: false, // 活动效果中全部门店排行榜模态窗
      searchOption: {
        activityStatus: '',
        activityType: '',
        dateValue: [],
        activityName: ''
      },
      data: [],
      subscribeActivityIndex: -1, // 下发活动的列表下标
      currentShowActivityEffectIndex: -1, // 当前查询活动效果的活动列表下表
      priorityTypeStr: '集团下发的促销活动生效，自动终止门店冲突活动',
      activityStatusTableData: [{ name: "未开始", code: 0 }, { name: "进行中", code: 1 }, { name: "已停止", code: 2 }, { name: "已过期", code: 3 }],
      activityTypeTableStoreData: [{ name: "整单折扣", code: 0 }, { name: "商品折扣", code: 1 }, { name: "满赠/每满赠", code: 2 }],
      activityTypeTableChainData: [{ name: "整单折扣", code: 0 }],
      pageNum: 1,
      pageSize: 10,
      total: 0,
      optionTime: {
        shortcuts: [
          {
            text: "今日",
            value() {
              const start = new Date();
              const end = new Date();

              start.setHours(0, 0, 0, 0);

              start.setTime(start.getTime());
              end.setTime(end.getTime());
              return [start, end];
            }
          },
          {
            text: "昨日",
            value() {
              const start = new Date();
              const end = new Date();

              start.setHours(0, 0, 0, 0);
              end.setHours(0, 0, 0, 0);

              start.setTime(start.getTime() - 3600 * 1000 * 24 * 1);
              end.setTime(end.getTime());
              return [start, end];
            }
          },
          {
            text: "本周",
            value() {
              const start = new Date();
              const end = new Date();

              start.setHours(0, 0, 0, 0);

              let weekDay = start.getDay();
              let distance = weekDay - 1;
              if (weekDay === 0) {
                distance = 6;
              }

              start.setTime(start.getTime() - 3600 * 1000 * 24 * distance);
              end.setTime(end.getTime());
              return [start, end];
            }
          },
          {
            text: "本月",
            value() {
              const start = new Date();
              const end = new Date();

              start.setHours(0, 0, 0, 0);

              let firstDayOfMonth = new Date(start.getFullYear(), start.getMonth(), 1);
              firstDayOfMonth.setTime(firstDayOfMonth.getTime());
              return [firstDayOfMonth, end];
            }
          },
          {
            text: "上月",
            value() {
              let nowData = new Date();
              let currentMonth = nowData.getMonth();
              let currentYear = nowData.getFullYear();
              let start = new Date(currentYear, currentMonth - 1, 1);
              let end = new Date(currentYear, currentMonth, 1);
              return [start, end];
            }
          }
        ]
      },
      startTime: [],
      columns: [
        {
          title: "序号",
          type: "index",
          width: 50,
          align: "center",
          className: "td-index"
        },
        {
          title: "活动名称",
          key: "activityName",
          width: 150,
          align: "center",
          headerAlign: "center"
        },
        {
          title: "活动类型",
          key: "activityType",
          width: 90,
          align: "center",
          headerAlign: "center",
          render: (h, params) => {
            let activityType = params.row.activityType;
            if (activityType === 0) {
              return h("p", "整单折扣");
            }
            if (activityType === 1) {
              return h("p", "商品折扣");
            }
            if (activityType === 2) {
              return h("p", "满赠/每满赠");
            }
          }
        },
        {
          title: "活动时间",
          key: "activityDateType",
          width: 140,
          align: "center",
          headerAlign: "center",
          render: (h, params) => {
            let activityDateType = params.row.activityDateType;
            if (activityDateType === 0) {
              return h("p", "长期有效");
            }
            if (activityDateType === 1) {
              let activityDate = params.row.activityDateStart;
              activityDate = activityDate + ' - ' + params.row.activityDateEnd;
              return h("p", activityDate);
            }
          }
        },
        {
          title: "活动状态",
          key: "activityStatus",
          width: 70,
          align: "center",
          headerAlign: "center",
          render: (h, params) => { //  0 =停止，1=进行中,2=已过期 3=未开始
            let activityStatus = params.row.activityStatus;
            if (activityStatus == 0) {
              return h("p", "已停止");
            } else if (activityStatus == 1) {
              return h("p", "进行中");
            } else if (activityStatus == 2) {
              return h("p", "已过期");
            } else if (activityStatus == 3) {
              return h("p", "未开始");
            }
          }
        },
        {
          title: "活动来源",
          key: "activityCreateSource",
          width: 80,
          align: "center",
          headerAlign: "center",
          render: (h, params) => {
            let activityCreateSource = params.row.activityCreateSource;
            if (activityCreateSource === 0) {
              return h("p", "门店");
            }
            if (activityCreateSource === 1) {
              return h("p", "集团");
            }
          }
        },
        {
          title: "活动说明",
          key: "activityDescription",
          width: 200,
          headerAlign: "center",
          align: "center"
        },
        {
          title: "操作",
          slot: "actions",
          align: "center",
          width: 280,
          minWidth: 120,
          className: "td-index"
        }
      ],
      activityStoreList: [], // 查看活动门店模态窗列表数据
      activityStoresTableColumns: [ // 查看活动门店模态窗列表列数据
        {
          title: '门店名称',
          key: 'storeName'
        },
        {
          title: '下发结果',
          key: 'distributeStatus',
          render: (h, params) => {
            let status = params.row.distributeStatus;
            if (status === 0) {
              return h("p", "等待下发");
            }
            if (status === 1) {
              return h("p", "下发成功");
            }
            if (status === 2) {
              return h("p", "下发失败");
            }
          }
        }
      ],
      activityStoresSelectTableColumns: [ // 选择活动门店模态窗列表列数据
        {
          type: 'selection',
          width: 60,
          align: 'center'
        },
        {
          title: '门店名称',
          key: 'storeName'
        }
      ],
      activityEffectColumns: [
        {
          title: "排名",
          type: "index",
          width: 60,
          align: "center",
          className: "td-index"
        },
        {
          title: "门店名称",
          key: "storeName",
          width: 150,
          align: "center",
          headerAlign: "center"
        },
        {
          title: "活动营业额",
          key: "storeOrderBillMoney",
          width: 150,
          align: "center",
          headerAlign: "center"
        }
      ],
      storeRankingTableloading: false,
      isSelectedShow7DayEffect: true,
      isSelectedShow15DayEffect: false,
      isSelectedShow30DayEffect: false,
      storeRankingData: [],
      storeRankingTableData: [],
      activityAnalysisListData: [
        {
          name: '活动营业额',
          amount: 0.00,
          img: activityRevenueImg,
          key: 'activityMoney'
        },
        {
          name: '活动营业收入',
          amount: 0.00,
          img: activityRevenueImg,
          key: 'activityReceiveMoney'
        },
        {
          name: '活动优惠金额',
          amount: 0.00,
          img: activityRevenueImg,
          key: 'activityPreferentialMoney'
        },
        {
          name: '订单量',
          amount: 0.00,
          img: activityRevenueImg,
          key: 'orderCount'
        },
        {
          name: '折前人均',
          amount: 0.00,
          img: activityRevenueImg,
          key: 'orderPriceOfAverage'
        },
        {
          name: '会员单量',
          amount: 0.00,
          img: activityRevenueImg,
          key: 'vipOrderCount'
        },
        {
          name: '非会员单量',
          amount: 0.00,
          img: activityRevenueImg,
          key: 'unVipOrderCount'
        }
      ],
      overviewListData: [
        {
          name: '活动营业额',
          amount: 0.00,
          img: activityRevenueImg,
          key: 'activityMoney'
        },
        {
          name: '活动营业收入',
          amount: 0.00,
          img: activityRevenueImg,
          key: 'activityReceiveMoney'
        },
        {
          name: '活动优惠金额',
          amount: 0.00,
          img: activityRevenueImg,
          key: 'activityPreferentialMoney'
        },
        {
          name: '订单量',
          amount: 0.00,
          img: activityRevenueImg,
          key: 'orderCount'
        },
        {
          name: '折前人均',
          amount: 0.00,
          img: activityRevenueImg,
          key: 'orderPriceOfAverage'
        },
        {
          name: '会员单量',
          amount: 0.00,
          img: activityRevenueImg,
          key: 'vipOrderCount'
        },
        {
          name: '非会员单量',
          amount: 0.00,
          img: activityRevenueImg,
          key: 'unVipOrderCount'
        }
      ],
      activityEffectTargetStoreName: '',
      activityEffectDateValue: [],
      showSelectStoreListModal: false, // 门店列表弹窗
      storeList: [],
      statisticsStoreList: [],
      activityEffectStoreList: [],
      activityEffectStoreCacheList: []
    };
  },
  methods: {
    init() {
      this.accountType = localStorage.getItem('userLoginType');
      if (this.accountType == 'company') {
        this.configChainActivityListColumns();
      }
      this.query();
    },
    configChainActivityListColumns() {
      this.columns = [
        {
          title: "序号",
          type: "index",
          width: 50,
          align: "center",
          className: "td-index"
        },
        {
          title: "活动名称",
          key: "activityName",
          width: 150,
          align: "center",
          headerAlign: "center"
        },
        {
          title: "活动类型",
          key: "activityType",
          width: 90,
          align: "center",
          headerAlign: "center",
          render: (h, params) => {
            let activityType = params.row.activityType;
            if (activityType === 0) {
              return h("p", "整单折扣");
            }
            if (activityType === 1) {
              return h("p", "商品折扣");
            }
            if (activityType === 2) {
              return h("p", "满赠/每满赠");
            }
          }
        },
        {
          title: "活动时间",
          key: "activityDateStart",
          width: 140,
          align: "center",
          headerAlign: "center",
          render: (h, params) => {
            let activityDateType = params.row.activityDateType;
            if (activityDateType === 0) {
              return h("p", "长期有效");
            }
            if (activityDateType === 1) {
              let activityDate = params.row.activityDateStart;
              activityDate = activityDate + ' - ' + params.row.activityDateEnd;
              return h("p", activityDate);
            }
          }
        },
        {
          title: "下发状态",
          key: "activityDistributeStatus",
          width: 70,
          align: "center",
          headerAlign: "center",
          render: (h, params) => {
            let activityDistributeStatus = params.row.activityDistributeStatus;
            if (activityDistributeStatus === 0) {
              return h("p", "未下发");
            } else {
              return h("p", "已下发");
            }
          }
        },
        {
          title: "活动门店",
          slot: "activityStore",
          width: 100,
          align: "center",
          headerAlign: "center"
        },
        {
          title: "活动状态",
          key: "activityStatus",
          width: 70,
          align: "center",
          headerAlign: "center",
          render: (h, params) => { //  0 =停止，1=进行中,2=已过期 3=未开始
            let activityStatus = params.row.activityStatus;
            if (activityStatus == 0) {
              return h("p", "已停止");
            } else if (activityStatus == 1) {
              return h("p", "进行中");
            } else if (activityStatus == 2) {
              return h("p", "已过期");
            } else if (activityStatus == 3) {
              return h("p", "未开始");
            }
          }
        },
        {
          title: "操作",
          slot: "actions",
          align: "center",
          width: 280,
          className: "td-index"
        }
      ]
    },
    // 分页
    changePage(pageNum) {
      this.pageNum = pageNum;
      this.query();
    },
    changePageSize(pageSize) {
      this.pageSize = pageSize;
      this.pageNum = 1;
      this.query();
    },
    onSearch() {
      this.pageNum = 1;
      this.query();
    },
    // 关闭促销活动详情模态窗
    closeModal() {
      this.showModal = false;
    // this.resetModalData();
    },
    // 查询
    query() {
      if (this.accountType == 'store') {
        this.storeActivityManageListPage();
      } else {
        this.chainActivityManageListPage();
      }
    },
    onReset() {
      this.searchOption.activityStatus = '';
      this.searchOption.activityType = '';
      this.searchOption.dateValue = [];
      this.searchOption.activityName = '';
    },
    // 触发日历
    handleDateChange(daterange) {
      this.searchOption.dateValue = daterange;
    },
    handleClose() {
      this.showDetail = false;
    },
    // 关闭创建促销活动模态窗回调
    handleCancel() {
      this.closeModal();
    },
    // 提交创建促销活动
    handleSubmit(params) {
      if (this.accountType == 'store') {
        this.storeActivityManageSave(params);
      } else {
        this.chainActivityManageSave(params);
      }
    },
    // 查看活动列表某个活动的活动门店
    handleShowActivityStore(index) {
      this.showActivityStoreModal = true;

      let tempActivityStoreList = this.data[index].activityStoreList;
      if (!tempActivityStoreList) {
        this.chainActivityStoreQuery(index);
      } else {
        this.activityStoreList = tempActivityStoreList;
      }
    },
    // 关闭活动门店模态窗
    handleActivityStoreListModalClose() {
      this.showActivityStoreModal = false;
    },
    // 清空选择的活动门店
    handleClearSelectedStore() {
      this.$refs.activityEffectStoreListSelection.selectAll(false);
    },
    // 取消活动门店模态窗操作
    handleActivityStoreModalCancel() {
      if (this.activityEffectStoreList.length > 0) {
        // 已经选了门店
        this.activityEffectStoreCacheList = this.activityEffectStoreList;
        this.$refs.activityEffectStoreListSelection.selectAll(false);
      } else {
        this.$refs.activityEffectStoreListSelection.selectAll(false);
      }
      this.showSelectStoreListModal = false;
    },
    // 确认活动门店模态窗操作
    handleActivityStoreModalSure() {
      if (this.activityEffectStoreCacheList.length < 1) {
        this.$Message.info('请至少选择1家门店');
      } else {
        this.activityEffectStoreList = this.activityEffectStoreCacheList;
        this.showSelectStoreListModal = false;
      }
    },
    // 查看活动详情
    handleShowActivityClick(index) {
      if (this.storeList.length < 1) {
        this.loadStoreListData();
      }
      let item = this.data[index];
      this.$refs.refSellPromotionModal.init(item, item.activityType + 3, true);
    },
    // 编辑活动
    handleEditActivityClick(index) {
      let item = this.data[index];
      this.$refs.refSellPromotionModal.init(item, item.activityType + 6, false);
    },
    // 终止活动
    handleEndActivityClick(index) {
      let item = this.data[index];
      this.storeActivityManageUpdateStatus(item.id, 0);
    },
    // 重启活动
    handleRestartActivityClick(index) {
      let item = this.data[index];
      this.storeActivityManageUpdateStatus(item.id, 1);
    },
    // 删除活动
    handleDeteleActivityClick(index) {
      let item = this.data[index];
      this.activityManageDelete(item.id);
    },
    // 下发活动
    handleDistributeActivityClick(index) {
      this.subscribeActivityIndex = index;
      this.showSubscribeActivityModal = true;
    },
    // 撤回活动
    handleUnSubscribeActivityClick(index) {
      let item = this.data[index];
      this.activityManageUnSubScribe(item.id);
    },
    // 设置活动效果时间
    setActivityEffectDateTime(days) {
      const start = new Date();
      const end = new Date();

      start.setHours(0, 0, 0, 0);
      start.setTime(start.getTime() - 3600 * 1000 * 24 * days);
      end.setTime(end.getTime());
      let startStr = Format(start, "yy-MM-dd hh:mm:ss");
      let endStr = Format(end, "yy-MM-dd hh:mm:ss");
      this.activityEffectDateValue = [startStr, endStr];
    },
    // 设置活动总效果数据
    setAnalysisListData(data, isReset) {
      for (let i = 0; i < this.activityAnalysisListData.length; i++) {
        let element = this.activityAnalysisListData[i];
        element.amount = isReset ? '0' : data[element.key];
      }
    },
    // 设置手动查询指定门店的营业效果数据
    setOverviewListData(data, isReset) {
      for (let i = 0; i < this.overviewListData.length; i++) {
        let element = this.overviewListData[i];
        element.amount = isReset ? '0' : data[element.key];
      }
    },
    // 查看活动效果
    handleShowActivityEffect(index) {
      this.currentShowActivityEffectIndex = index;
      this.setActivityEffectDateTime(7);
      this.showActivityEffectModal = true;

      let item = this.data[index];
      let effectAnalysisInfo = item.effectAnalysisInfo;
      let statisticsStoreChart = item.statisticsStoreChart;

      if (!effectAnalysisInfo || !statisticsStoreChart) {
        const Loading = this.$myLoading({
          content: "正在查询活动效果，请稍后…"
        });

        let _this = this;
        Promise
          .all([
            this.chainActivityStatisticsInfo({ activityId: item.id }),
            this.chainActivityStatisticsStoreChart({ activityId: item.id })
          ])
          .then((result) => {
            if (result && result.length > 1) {
              this.setAnalysisListData(result[0], false);
              this.storeRankingData = result[1];
              if (this.storeRankingData.length > 10) {
                this.storeRankingTableData = this.storeRankingData.slice(0, 10);
              } else {
                this.storeRankingTableData = this.storeRankingData;
              }
            }
            this.closeLoading(Loading);
          });
      }
    },
    // 切换活动效果显示天数
    handleSelectShowDayCount(days) {
      if (days == 7) {
        this.isSelectedShow7DayEffect = true;
        this.isSelectedShow15DayEffect = false;
        this.isSelectedShow30DayEffect = false;
      } else if (days == 15) {
        this.isSelectedShow7DayEffect = false;
        this.isSelectedShow15DayEffect = true;
        this.isSelectedShow30DayEffect = false;
      } else if (days == 30) {
        this.isSelectedShow7DayEffect = false;
        this.isSelectedShow15DayEffect = false;
        this.isSelectedShow30DayEffect = true;
      }

      this.setActivityEffectDateTime(days);
    },
    // 加载门店列表数据
    loadStoreListData() {
      let storeInfo = this.$store.state.storeInfo;
      if (storeInfo.storeList.length == 0) {
        let storeListJSON = localStorage.getItem('storeList');
        if (storeListJSON != 'undefined' && storeListJSON != '') {
          storeInfo.storeList = JSON.parse(storeListJSON);
        }
      }

      this.storeList = storeInfo.storeList;
      for (let i = 0; i < this.storeList.length; i++) {
        const item = this.storeList[i];
        item.isSelected = false;
      }
    },
    // 显示选择活动效果门店模态窗
    handleSelectStore() {
      let item = this.data[this.currentShowActivityEffectIndex];
      let statisticsStoreList = item.statisticsStoreList;

      if (statisticsStoreList) {
        if (this.activityEffectStoreList.length > 0) {
          let tempStatisticsStoreList = JSON.stringify(statisticsStoreList);
          if (tempStatisticsStoreList.length < 1) { return; }
          tempStatisticsStoreList = JSON.parse(tempStatisticsStoreList);

          this.activityEffectStoreList.map((selectedItem) => {
            tempStatisticsStoreList.map((item) => {
              if (item.storeCode == selectedItem.storeCode) {
                item['_checked'] = true;
              }
            })
          });
          this.statisticsStoreList = tempStatisticsStoreList;
        }
      } else {
        this.chainActivityStatisticsStoreList({ activityId: item.id });
      }

      this.showSelectStoreListModal = true;
    },
    // 选择活动效果门店
    activityEffectStoreSelcted(storeList) {
      this.activityEffectStoreCacheList = storeList;
    },
    handleActivityEffectDateChange(daterange) {
      this.activityEffectDateValue = daterange;
    },
    // 活动效果-点击查询
    onSearchActivityEffect() {
      const Loading = this.$myLoading();
      let item = this.data[this.currentShowActivityEffectIndex];

      var params = {
        activityId: item.id,
        beginDate: this.activityEffectDateValue[0],
        endDate: this.activityEffectDateValue[1]
      };

      if (this.activityEffectStoreList && this.activityEffectStoreList.length > 0) {
        var storeCodeListStr = this.activityEffectStoreList[0].storeCode;
        for (var i = 1; i < this.activityEffectStoreList.length; i++) {
          var element = this.activityEffectStoreList[i];
          storeCodeListStr = storeCodeListStr + ',' + element.storeCode;
        }
        params['storeCodeList'] = [storeCodeListStr];
      }

      Promise.all([this.chainActivityStatisticsInfo(params)]).then((result) => {
        if (result.length > 0) {
          this.setOverviewListData(result[0], false);
        }
        this.closeLoading(Loading);
      });
    },
    // 关闭活动效果模态窗
    closeActivityEffectModal() {
      this.activityEffectStoreList = [];
      this.activityEffectStoreCacheList = [];
      this.storeRankingData = [];
      this.setAnalysisListData(null, true);
      this.setOverviewListData(null, true);
    },
    // 活动效果-点击重置
    onResetActivityEffect() {
      this.activityEffectStoreList = [];
      this.activityEffectStoreCacheList = [];
      this.handleSelectShowDayCount(7);
    },
    // 展示全部门店列表
    handleShowAllStoreRanking() {
      this.showAllStoreRankingModal = true;
    },
    // 关闭全部门店模态窗
    handleStoreRankingModalClose() {
      this.showAllStoreRankingModal = false;
    },
    // 下发活动预选方案点击取消
    handleSubscribeActivityCancel() {
      this.showSubscribeActivityModal = false;
    },
    // 下发活动预选方案点击确定
    handleSubscribeActivitySure() {
      this.chainActivityManageDistribute();
      this.showSubscribeActivityModal = false;
    },
    // 单店-分页查询活动列表
    async storeActivityManageListPage() {
      const Loading = this.$myLoading();
      var item = {
        page: this.pageNum,
        pageSize: this.pageSize,
        activityStatus: this.searchOption.activityStatus,
        activityType: this.searchOption.activityType,
        activityName: this.searchOption.activityName
      };
      if (this.searchOption.dateValue && this.searchOption.dateValue.length > 1) {
        item['beginDate'] = this.searchOption.dateValue[0];
        item['endDate'] = this.searchOption.dateValue[1];
      }
      const { data, status } = await storeActivityManageListPage(item);
      if (status == 200 && data.code == 200) {
        this.total = data.data.total;
        this.data = data.data.list;
      } else {
        this.$Message.error(data.message);
      }

      this.Tableloading = false;
      this.closeLoading(Loading);
    },
    // 连锁-分页查询活动列表
    async chainActivityManageListPage() {
      const Loading = this.$myLoading();
      const item = {
        page: this.pageNum,
        pageSize: this.pageSize,
        startTime: this.searchOption.dateValue[0],
        endTime: this.searchOption.dateValue[1],
        refundMode: this.refundMode,
        cashierCode: this.cashierCode,
        orderNo: this.orderNo,
        refundNo: this.refundNo,
        productName: this.productName,
        productBarcode: this.productBarcode
      };
      const { data, status } = await chainActivityManageListPage(item);
      if (status == 200 && data.code == 200) {
        this.total = data.data.total;
        this.data = data.data.list;
      } else {
        this.$Message.error(data.message);
      }

      this.Tableloading = false;
      this.closeLoading(Loading);
    },
    // 连锁查看活动门店
    async chainActivityStoreQuery(index) {
      const Loading = this.$myLoading({
        content: "正在查询活动门店，请稍后…"
      });

      let activityId = this.data[index].id;
      const { data } = await chainActivityStoreQuery({ activityId });
      if (data.code == 200 && data.result) {
        this.data[index].activityStoreList = data.data;
        this.activityStoreList = data.data;
      } else {
        this.$Message.error(data.message);
      }
      this.closeLoading(Loading);
    },
    // 更新单店促销活动
    async storeActivityManageSave(params) {
      const Loading = this.$myLoading({
        content: "正在更新促销活动，请稍后…"
      });

      const { data } = await storeActivityManageSave(params);
      if (data.code == 200 && data.result) {
        this.$Message.success('更新促销活动成功');
        this.$refs.refSellPromotionModal.disappear();
        this.query()
      } else {
        this.$Message.error(data.message);
      }
      this.closeLoading(Loading);
    },
    // 更新连锁促销活动
    async chainActivityManageSave(params, isUpdate) {
      const Loading = this.$myLoading({
        content: "正在更新促销活动，请稍后…"
      });

      const { data } = await chainActivityManageSave(params);
      if (data.code == 200 && data.result) {
        this.$Message.success('更新促销活动成功');
        this.$refs.refSellPromotionModal.disappear();
        this.query()
      } else {
        this.$Message.error(data.message);
      }
      this.closeLoading(Loading);
    },
    // 删除促销活动
    async activityManageDelete(activityId) {
      const Loading = this.$myLoading({
        content: "正在删除促销活动，请稍后…"
      });

      const { data } = await activityManageDelete({ activityId: activityId });
      if (data.code == 200 && data.result) {
        this.$Message.success('删除成功');
        this.query();
      } else {
        this.$Message.error(data.message);
      }
      this.closeLoading(Loading);
    },
    // 下发促销活动
    async chainActivityManageDistribute() {
      const Loading = this.$myLoading({
        content: "正在下发促销活动，请稍后…"
      });

      var priorityType = 1;
      if (this.priorityTypeStr == '继续使用门店促销活动，集团促销下发时自动终止') {
        priorityType = 0;
      }

      let params = { activityId: this.data[this.subscribeActivityIndex].id, priorityType: priorityType };
      const { data } = await chainActivityManageDistribute(params);
      if (data.code == 200 && data.result) {
        this.$Message.success('下发成功');
        this.chainActivityManageListPage();
      } else {
        this.$Message.error(data.message);
      }
      this.closeLoading(Loading);
    },
    // 撤回促销活动
    async activityManageUnSubScribe(activityId) {
      const Loading = this.$myLoading({
        content: "正在撤回促销活动，请稍后…"
      });

      const { data } = await activityManageUnSubScribe({ activityId: activityId });
      if (data.code == 200 && data.result) {
        this.$Message.success('撤回成功');
        this.chainActivityManageListPage();
      } else {
        this.$Message.error(data.message);
      }
      this.closeLoading(Loading);
    },
    // 查询活动效果
    async chainActivityStatisticsInfo(params) {
      return new Promise((resolve, reject) => {
        chainActivityStatisticsInfo(params)
          .then((result) => {
            if (result.data.code == 200 && result.status == 200) {
              resolve(result.data.data);
            } else {
              _this.$Message.error(result.data.message);
              resolve(false);
            }
          })
      })
    },
    // 连锁-活动效果-活动营业额排行榜
    async chainActivityStatisticsStoreChart(params) {
      return new Promise((resolve, reject) => {
        chainActivityStatisticsStoreChart(params)
          .then((result) => {
            if (result.data.code == 200 && result.status == 200) {
              resolve(result.data.data);
            } else {
              _this.$Message.error(result.data.message);
              resolve(false);
            }
          })
      })
    },
    // 连锁-查询活动关联门店列表
    async chainActivityStatisticsStoreList(params) {
      const Loading = this.$myLoading({
        content: "正在查询活动相关门店，请稍后…"
      });

      const { data } = await chainActivityStatisticsStoreList(params);
      if (data.code == 200 && data.result) {
        this.data[this.currentShowActivityEffectIndex]['statisticsStoreList'] = data.data;
        this.statisticsStoreList = data.data;
      } else {
        this.$Message.error(data.message);
      }
      this.closeLoading(Loading);
    },
    // 单店-更新活动状态
    async storeActivityManageUpdateStatus(activityId, activityStatus) {
      const Loading = this.$myLoading({
        content: activityStatus == 0 ? '正在终止促销活动，请稍后…' : '正在启用促销活动，请稍后…'
      });

      const { data } = await storeActivityManageUpdateStatus({ activityId, activityStatus });
      if (data.code == 200 && data.result) {
        this.$Message.success(activityStatus == 0 ? '终止成功' : '启用成功');
        this.query();
      } else {
        this.$Message.error(data.message);
      }
      this.closeLoading(Loading);
    },
    closeLoading(Loading) {
      let timer = setTimeout(() => {
        clearTimeout(timer);
        timer = null;
        Loading && Loading.close();
      }, 300);
    }
  },
  components: {
    sellPromotion: sellPromotionModal
  },
  mounted: function() {
    this.init();
  }
};
</script>
<style lang="less">
.space-left {
  padding-left: 20px;
}
.operTime button {
  margin-left: 15px;
}
.ivu-input-large {
  height: 32px !important;
}
.vertical-center-modal{
    display: flex;
    align-items: center;
    justify-content: center;

    .ivu-modal{
        top: 0;
    }
}
.select-table-item {
  text-align: left;
  height: 32px !important;
  font-size: 14px;
  display: inline-block;
  width: 10%;
}
.order-no-col {
  width: 21%;
}
.ivu-input {
  height: 32px !important;
}
.tabsList {
  margin-top: 15px;
}
.search-label {
  width: 100px;
  margin-right: 10px;
  text-align: right;
}
.query-btn {
  margin-left: 2.5% !important;
}
.reset-btn {
  margin-left: 1.5% !important;
}
/** 活动分析 */
.activity-effect-analysis {
  display: flex;
  flex-direction: column;
  border: 1px solid #f5f5f5;

  &>span {
    margin: 10px 0 0 15px;
    font-size: 14px;
    font-weight: bold;
  }

  &-list {
    display: flex;
    flex-wrap: wrap;
    margin: 0px 50px 20px 60px;
  }

  &-list-item {
    display: flex;
    width: 200px;
    height: 100px;
    align-items: center;

    &>img {
      width: 44px;
      height: 44px;
      margin-left: 30px;
    }
  }

  &-list-item-right {
    display: flex;
    flex-direction: column;

    &>p {
      text-align: center;
    }
  }

  &-list-item-separate {
    display: block;
    width: 1px;
    height: 80px;
    margin-left: auto;
    background-color: #f5f5f5;
  }
}

/** 活动概览 */
.activity-effect-overview {
  display: flex;
  flex-direction: column;
  border: 1px solid #f5f5f5;
  margin-top: 10px;

  &-store-name {
    display: inline-block;
    height: 15px;
    color: #F29D42;
    margin: 30px 0px;
    font-weight: 500;
  }

  .overview-dateLabel {
    margin: 0px 5px 0px 35px;
  }

  &-date-selected {
    color: #F29D42;
    font-size: 13px;
    font-weight: 500;
    margin: 0px 10px;
  }

  &-date-normal {
    color: #000;
    font-size: 13px;
    font-weight: 500;
    margin: 0px 10px;
  }

  &-separate {
    display: block;
    width: 100%;
    height: 1px;
    background-color: #f5f5f5;
  }

  &-separate {
    display: block;
    width: 100%;
    height: 1px;
    background-color: #f5f5f5;
  }

  &-list {
    display: flex;
    padding-left: 30px;
  }

  &-list-item {
    display: flex;
    flex-direction: column;
    width: 145px;

    &-name {
      text-align: center;
      margin: 20px 0px;
    }

    &-value {
      text-align: center;
      margin: 5px 0px 30px 0px;
    }
  }
}
/** 活动门店排行 */
.activity-effect-ranking {
  padding: 30px 0px 0px 45px;

  &-title {
    display: inline-block;
    margin: 0px 20px 15px 0px;
  }
}
</style>
